<template>
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
      <!-- 标题栏 -->
      <div class="p-4 border-b border-gray-100 flex justify-between items-center">
        <h3 class="font-medium text-gray-900">
          {{ isFollowers ? '粉丝' : '关注' }} ({{ totalCount }})
        </h3>
        
        <div class="relative">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索..."
            class="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
          >
          <i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
        </div>
      </div>
      
      <!-- 用户列表 -->
      <div v-if="loading" class="text-center py-12">
        <Loading />
      </div>
      
      <div v-else-if="users.length === 0" class="text-center py-12 text-gray-500">
        {{ isFollowers ? '暂无粉丝' : '暂无关注' }}
      </div>
      
      <div v-else>
        <div v-for="user in users" :key="user.id" class="p-4 border-b border-gray-100 hover:bg-gray-50 transition">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <UserAvatar :user="user" size="md" />
              
              <div class="ml-3">
                <div class="font-medium text-gray-900">
                  <router-link :to="{ name: 'Profile', params: { id: user.id } }">
                    {{ user.username }}
                  </router-link>
                </div>
                <div class="text-sm text-gray-500 mt-0.5">
                  {{ user.bio || '暂无简介' }}
                </div>
              </div>
            </div>
            
            <div>
              <button
                v-if="!isCurrentUser(user.id) && !isFollowing(user.id)"
                class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-1.5 px-4 rounded-md transition duration-300 text-sm"
                @click="handleFollow(user.id)"
              >
                关注
              </button>
              
              <button
                v-else-if="!isCurrentUser(user.id) && isFollowing(user.id)"
                class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-1.5 px-4 rounded-md transition duration-300 text-sm"
                @click="handleUnfollow(user.id)"
              >
                已关注
              </button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 加载更多 -->
      <div v-if="hasMore && !loading" class="p-4 text-center">
        <button
          class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-md transition duration-300"
          @click="loadMore"
        >
          加载更多
        </button>
      </div>
    </div>
  </template>
  
  <script>
  import { ref, computed, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  import { useAuthStore } from '@/store/modules/auth'
  import { useUserStore } from '@/store/modules/user'
  import UserAvatar from '@/components/user/UserAvatar.vue'
  import Loading from '@/components/common/Loading.vue'
  
  export default {
    components: {
      UserAvatar,
      Loading
    },
    
    props: {
      userId: {
        type: String,
        required: false
      },
      isFollowers: {
        type: Boolean,
        default: true
      }
    },
    
    setup(props) {
      const route = useRoute()
      const authStore = useAuthStore()
      const userStore = useUserStore()
      
      const currentUserId = computed(() => props.userId || route.params.id)
      const currentUser = computed(() => authStore.currentUser)
      const users = ref([])
      const loading = ref(false)
      const error = ref(null)
      const page = ref(1)
      const hasMore = ref(true)
      const searchQuery = ref('')
      const totalCount = ref(0)
      
      // 判断是否是当前登录用户
      const isCurrentUser = (userId) => {
        return currentUser.value?.id === userId
      }
      
      // 判断是否已关注
      const isFollowing = (userId) => {
        return currentUser.value?.following?.some(following => following.id === userId)
      }
      
      // 加载用户列表
      const fetchUsers = async (reset = false) => {
        if (loading.value) return
        
        if (reset) {
          page.value = 1
          hasMore.value = true
        }
        
        loading.value = true
        error.value = null
        
        try {
          const params = {
            page: page.value,
            limit: 10,
            search: searchQuery.value
          }
          
          let response
          
          if (props.isFollowers) {
            response = await userStore.fetchUserFollowers(currentUserId.value, params)
            totalCount.value = response.totalCount || 0
          } else {
            response = await userStore.fetchUserFollowing(currentUserId.value, params)
            totalCount.value = response.totalCount || 0
          }
          
          if (reset) {
            users.value = response.items || []
          } else {
            users.value = [...users.value, ...(response.items || [])]
          }
          
          page.value++
          hasMore.value = (response.items || []).length > 0
        } catch (err) {
          error.value = err.message || '加载失败'
        } finally {
          loading.value = false
        }
      }
      
      // 加载更多
      const loadMore = () => {
        if (!loading.value && hasMore.value) {
          fetchUsers(false)
        }
      }
      
      // 关注用户
      const handleFollow = async (userId) => {
        try {
          await userStore.followUser(userId)
          // 更新本地状态
          users.value = users.value.map(user => {
            if (user.id === userId) {
              return { ...user, isFollowing: true }
            }
            return user
          })
        } catch (error) {
          console.error('Error following user:', error)
        }
      }
      
      // 取消关注
      const handleUnfollow = async (userId) => {
        try {
          await userStore.unfollowUser(userId)
          // 更新本地状态
          users.value = users.value.map(user => {
            if (user.id === userId) {
              return { ...user, isFollowing: false }
            }
            return user
          })
        } catch (error) {
          console.error('Error unfollowing user:', error)
        }
      }
      
      // 监听搜索查询变化
      watch(searchQuery, () => {
        fetchUsers(true)
      })
      
      // 初始化加载
      onMounted(() => {
        fetchUsers(true)
      })
      
      return {
        users,
        loading,
        error,
        hasMore,
        searchQuery,
        totalCount,
        isCurrentUser,
        isFollowing,
        loadMore,
        handleFollow,
        handleUnfollow
      }
    }
  }
  </script>